package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.redisson.api.RAtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-12-14
 */
@RestController
public class ChoujiangController {

    private static final Logger logger = LoggerFactory.getLogger(ChoujiangController.class);

    @Autowired
    private IChoujiangService choujiangService;
    @Autowired
    private IChoujiangLogService choujiangLogService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IShareService shareService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("/api/choujiang/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = choujiangService.selectPage(page, new EntityWrapper<Choujiang>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    //添加抽奖奖品
    @RequestMapping("/api/choujiang/add")
    @ResponseBody
    public Jinfo choujiangAdd(@Valid Choujiang choujiang,
                              HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (choujiang.getId() == null) {
            choujiang.setCreatetime(new Date());
            choujiang.setMid(ObjectUtil.getMid());
            choujiang.setMpid(ObjectUtil.getMpid());
            choujiang.setUid(ObjectUtil.getUid());
            choujiang.setSid(ObjectUtil.getSid());
            choujiang.setLeagueid(redisService.getLeagueid(ObjectUtil.getSid()));
            choujiang.setState(-1);
        } else {
            choujiang.setModifytime(new Date());
            choujiang.setModifier(ObjectUtil.getUid());
        }
        choujiang.insertOrUpdate();

        info.setInfo(choujiang);
        return info;
    }

    @RequestMapping("/api/choujiang/modify")
    @ResponseBody
    public Jinfo choujiangUpdate(HttpServletRequest req,
                                 Choujiang choujiang) {
        Jinfo info = new Jinfo();
        choujiang.setModifytime(new Date());
        choujiang.updateById();
        return info;
    }

    @RequestMapping("/api/choujiang/detail")
    @ResponseBody
    public Jinfo getChoujiangDetailById(@RequestParam("token") String token,
                                        @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Choujiang choujiang = choujiangService.selectById(id);
        info.setInfo(choujiang);
        return info;
    }

    @RequestMapping("/api/choujiang/jplist")
    @ResponseBody
    public Jinfo jplist() {

        Jinfo info = new Jinfo();
        Page page = new Page(1, 8);
        page = choujiangService.selectPage(page, new EntityWrapper<Choujiang>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("state", 1)
                .orderBy("sort", true)
        );
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/choujiang/sjjplist")
    @ResponseBody
    public Jinfo sjjplist() {

        Jinfo info = new Jinfo();
        Page page = new Page(1, 8);
        page = choujiangService.selectPage(page, new EntityWrapper<Choujiang>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("sid", ObjectUtil.getSid())
                .eq("state", 1)
                .orderBy("sort", true)
        );
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/choujiang/chou")
    @ResponseBody
    public Jinfo chou(Long gid, Integer iszhong, Long jiangid,
                      @RequestParam(value = "oid", required = false) Long oid) {

        Jinfo info = new Jinfo();

        ChoujiangLog choulog = new ChoujiangLog();
        choulog.setGid(gid);
        choulog.setOid(oid);
        choulog.setIsZhong(iszhong);
        choulog.setCjid(jiangid);
        if (jiangid != null) {
            Choujiang choujiang = choujiangService.selectById(jiangid);
            if (choujiang != null) choulog.setJtype(choujiang.getJtype());
            if (choujiang != null) choulog.setLevel(choujiang.getLevel());
            if (choujiang != null) choulog.setName(choujiang.getName());
            if (choujiang != null) choulog.setPic(choujiang.getPic());
            if (choujiang != null) choulog.setSid(choujiang.getSid());
        }

        choulog.setMid(ObjectUtil.getMid());
        choulog.setMpid(ObjectUtil.getMpid());

        choulog.setUid(ObjectUtil.getUid());
        choulog.setCreatetime(new Date());
        choulog.setCjdate(DateUtil.getToday());
        User user = redisService.getUser();

        if (gid == null) {
            if (user == null) return info;
            choulog.setUname(user.getNickName());
            choulog.setPhone(user.getPhone());
            logger.debug("------------------choujiang/chou------------------user.getAvatarPic()=" + user.getAvatarPic());
            choulog.setAvatarpic(user.getAvatarPic());
        } else {
            Order order = orderService.selectOne(new EntityWrapper<Order>().ge("status", 1)
                    .eq("gid", gid).eq("uid", ObjectUtil.getUid()));
            choulog.setUname(order.getLinkman());
            choulog.setPhone(order.getPhone());
            choulog.setAvatarpic(user.getAvatarPic());
        }
        choulog.insert();
        info.setData(choulog.getId());

        if(iszhong == 1) choujiangService.lingjiang(choulog);

        return info;
    }

    @RequestMapping("/api/choujiang/choucha")
    @ResponseBody
    public Jinfo choucha() {

        Jinfo info = new Jinfo();
        int count = choujiangLogService.selectCount(new EntityWrapper<ChoujiangLog>()
                .eq("uid", ObjectUtil.getUid())
                .eq("cjdate", DateUtil.getToday())
        );
        info.setInfo(count);

        //今日分享抽奖次数
        int todayshare = shareService.selectCount(new EntityWrapper<Share>()
                .eq("uid", ObjectUtil.getUid())
                .eq("sharedate", DateUtil.getToday())
                .like("path", "/pages/zhuanpan/zhuanpan/")
        );
        info.setData(todayshare);

        return info;
    }

    //cjid：抽奖ID
    //gid：抽奖活动订单
    @RequestMapping("/api/choujiang/lingjiang")
    @ResponseBody
    public Jinfo lingjiang(@RequestParam("cjid") Long cjid,
                           @RequestParam(value = "gid", required = false) Long gid,
                           @RequestParam(value = "oid", required = false) Long oid) {

        Jinfo info = new Jinfo();

        Choujiang jiang = choujiangService.selectById(cjid);

        ChoujiangLog choujiangLog = choujiangLogService.selectOne(new EntityWrapper<ChoujiangLog>()
                .eq("uid", ObjectUtil.getUid())
                .eq("islingqu", -1)
                .eq("cjdate", DateUtil.getToday())
        );
        if (choujiangLog.getIsZhong() == -1) {
            logger.debug("----------------------choujiangLog.getIsZhong() = " + choujiangLog.getIsZhong());
            return info;
        }
        User ruser = redisService.getUser();
        choujiangLog.setName(jiang.getName());
        choujiangLog.setPic(jiang.getPic());
        choujiangLog.setCjid(cjid);
        choujiangLog.setOid(oid);
        choujiangLog.setPic(jiang.getPic());
        choujiangLog.setLevel(jiang.getLevel());
        choujiangLog.setJtype(jiang.getJtype());
        choujiangLog.setIslingqu(1);
        choujiangLog.setAvatarpic(ruser.getAvatarPic());
        choujiangLog.updateById();

        Long uid = ObjectUtil.getUid();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();

        //@1：积分；2：优惠券；3：商品；4：现金红包；5：谢谢参与
        if (jiang.getJtype() == 1) {
            JifenFlow jf = new JifenFlow();

            jf.setNum(new BigDecimal(jiang.getValue()));//充值金额（元）取整
            jf.setSn(StringUtil.getSnNo("J"));
            jf.setIsConfirm(1);
            jf.setState(1);
            jf.setIotype(IotypeEnum.input.getVal());//积分+
            jf.setJftype(JftypeEnum.zhongjiang.getVal());//积分返消费
            jf.setCreatetime(new Date());
            jf.setUid(uid);
            jf.setMid(mid);
            jf.setMpid(mpid);
            jf.setRemark("每日抽奖奖励积分");
            jf.insert();

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            long version = jifen.getVersion();
            BigDecimal total = jifen.getTotal();
            Jifen njifen = new Jifen();

            njifen.setTotal(jf.getIotype() == 1 ? total.add(jf.getNum()) : total.subtract(jf.getNum()));
            njifen.setModifytime(new Date());
            njifen.setModifier(ObjectUtil.getUid());
            njifen.setVersion(version + 1);

            jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
        } else if (jiang.getJtype() == 2) {
            CouponTpl ctpl = couponTplService.selectById(jiang.getJid());
            //优惠券
            Coupon coupon = new Coupon();
            coupon.setIsUnused(1);//未使用
            coupon.setIsUsed(0);//已使用
            coupon.setIsForever(ctpl.getIsForever());//永久有效
            coupon.setIsOutdate(0);//已过期
            coupon.setState(1);

            coupon.setMid(mid);
            coupon.setMpid(mpid);
            coupon.setUid(uid);
            coupon.setSid(ctpl.getSid());
            coupon.setCreatetime(new Date());

            coupon.setTplid(jiang.getJid());
            coupon.setType(ctpl.getType());
            coupon.setName(ctpl.getName());
            coupon.setSlogo(ctpl.getSlogo());
            coupon.setSname(ctpl.getSname());
            coupon.setRemark(ctpl.getRemark());

            coupon.setCno(StringUtil.getQuanCode(mid));
            coupon.setSn(null);

            coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
            coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
            coupon.setCost(ctpl.getCost());
            coupon.setUsemin(ctpl.getUsemin());
            coupon.setOriginType(Qgettype.choujiang.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值;5：任务奖励;5：抽奖&
            //券核销了，应该触发关闭该活动订单状态

            coupon.insert();

            CouponTpl ctpl2 = new CouponTpl();
            ctpl2.setUse(ctpl.getUse() + 1);
            ctpl2.setId(ctpl.getId());
            ctpl2.updateById();

        } else if (jiang.getJtype() == 3) {
            //领取商品 ===待实现

        } else if (jiang.getJtype() == 4) {
            //虚拟币
            Boolean flag = false;
            Account naccount = new Account();
            BigDecimal zero = new BigDecimal(0);
            AccountFlow af = new AccountFlow();
            af.setRealpay(zero);
            af.setAmount(zero);
            af.setDikou(new BigDecimal(jiang.getValue()));
            af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

            User user = redisService.getUser();
            af.setNickname(user != null ? user.getNickName() : null);
            af.setHeadimg(user != null ? user.getAvatarPic() : null);
            af.setPhone(user != null ? user.getPhone() : null);

            af.setUid(uid);
            af.setMid(mid);
            af.setMpid(mpid);
            af.setIsConfirm(-1);
            af.setState(1);

            af.setIotype(IotypeEnum.input.getVal());//1:入账
            af.setXftype(XftypeEnum.choujiang.getVal());//1:充值

            af.setCreatetime(new Date());
            af.setSn(StringUtil.getSnNo("J"));
            af.setRemark("每日抽奖");
            af.setTradetime(new Date());
            af.setCreatetime(new Date());

            while (af != null && !flag) {
                Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                if (account == null) {
                    logger.error(">>>account at uid=" + uid + " not exist and sn=" + af.getSn());
                    break;
                }

                Long version = account.getVersion();
                BigDecimal total = account.getTotal();
                BigDecimal mamount = account.getMamount();

                naccount.setTotal(total.add(af.getRealpay()).add(af.getDikou()));//getRealpay=实付+返现
                naccount.setMamount(mamount.add(af.getDikou()));

                naccount.setModifytime(new Date());
                naccount.setId(account.getId());
                naccount.setModifier(uid);
                naccount.setVersion(version + 1);

                af.setConfirmDate(new Date());
                af.setIsConfirm(1);//确认
                af.setLasttotal(account.getTotal());
                af.setLastamount(account.getAmount());
                flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
                if (flag) af.insert();
                logger.debug(">>>accountService.update flag=" + flag);
            }

            //摇奖红包属于营销金额，当产生交易时，商户端才会有变化
        }

        if (oid != null && oid > 0) {
            Order order = orderService.selectOne(new EntityWrapper<Order>()
                    .setSqlSelect("id,shipper_method shipperMethod").eq("id", oid));

            order.setId(oid);
            order.setStatus(StatusEnum.receving.getVal());
            //==待实现 更新是否发货
            //要求快递的话发货
            if (order.getShipperMethod() != null
                    && order.getShipperMethod() == 1) order.setFhstate(1);
            else order.setFhstate(2);
            //等核销完之后 更新状态

            order.setModifytime(new Date());
            order.setModifier(ObjectUtil.getUid());
            order.updateById();
        }

        if (gid != null && gid > 0) {

            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>()
                    .setSqlSelect("id,ptotal,stores").eq("id", gid));
            goods.setId(gid);
            goods.setPtotal(goods.getPtotal() == null ? 1 : goods.getPtotal() + 1);//活动中奖人数
            goods.setStores(goods.getStores() - 1);//活动中奖人数

            if (goods.getStores() <= 0) {
                goods.setStatus(Gstatus.over.getVal());
            }
            goods.setModifytime(new Date());
            goods.setModifier(ObjectUtil.getUid());
            logger.debug("------------------lingjiang goods=" + JSON.toJSONString(goods));
            goods.updateById();

            //更新活动中奖商品
            Order order = orderService.selectOne(new EntityWrapper<Order>()
                    .setSqlSelect("id,goods_number goodsNumber")
                    .eq("gid", gid).eq("uid", ObjectUtil.getUid()));
            order.setGoodsNumber(order.getGoodsNumber() + 1);
            order.setStatus(StatusEnum.receving.getVal());
            order.updateById();
        }

        return info;
    }

    //中奖列表(门诊版抽奖)
    @RequestMapping("/api/choujiang/zhonglist")
    @ResponseBody
    public Jinfo zhonglist(@RequestParam(value = "gid", required = false) Long gid) {

        Jinfo info = new Jinfo();
        Page page = new Page(1, 20);
        Wrapper<ChoujiangLog> entity = new EntityWrapper<ChoujiangLog>()
                .setSqlSelect("id,name,uname,name,cjdate,pic,avatarpic,isguoqi,jtype")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("is_zhong", 1)
                .orderBy("id", false);
        if (gid != null && gid.longValue() > 0) entity.eq("gid", gid);
        Page<ChoujiangLog> pdata = choujiangLogService.selectPage(page, entity);

        logger.debug("------------------lingjiang pdata.getRecords()=" + JSON.toJSONString(pdata.getRecords()));
        info.setInfo(pdata.getRecords());

        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            return info;
        }

        if (gid != null && gid.longValue() > 0) {
            //extkey1: e.info.extkey1,//每日抽奖数
            //extkey2: e.info.extkey2,//中奖率
            //extkey3: e.info.extkey3,//单人中奖数
            Goods goods = goodsService.selectById(gid);

        }

        Long mpid = ObjectUtil.getMpid();
        //查询所有中奖项目
        Page jpage = new Page(1, 8);
        jpage = choujiangService.selectPage(page, new EntityWrapper<Choujiang>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .orderBy("sort", true)
        );
        List<Choujiang> jplist = jpage.getRecords();
        //extkey1: e.info.extkey1,//每日抽奖数
        //extkey2: e.info.extkey2,//中奖率
        //extkey3: e.info.extkey3,//单人中奖数
        //计算头等奖+二等奖+三等奖+四等奖
        int maxnum1 = 0;
        int maxnum2 = 0;
        int maxnum3 = 0;
        int maxnum4 = 0;
        int maxnumPuser1 = 0;
        int maxnumPuser2 = 0;
        int maxnumPuser3 = 0;
        int maxnumPuser4 = 0;

        int leftnum1 = 0;
        int leftnum2 = 0;
        int leftnum3 = 0;
        int leftnum4 = 0;

        Integer myleftnum1 = -1;//每人剩余
        Integer myleftnum2 = -1;
        Integer myleftnum3 = -1;
        Integer myleftnum4 = -1;

        int num1Idx = 0;
        int num2Idx = 0;
        int num3Idx = 0;
        int num4Idx = 0;
        int m = 0;
        //
        for (Choujiang jiang : jplist) {
            if (jiang.getLevel() != null && jiang.getLevel() == 1) {
                maxnum1 = jiang.getMaxnum() == null ? 0 : jiang.getMaxnum();
                maxnumPuser1 = jiang.getMaxnumPuser() == null ? 0 : jiang.getMaxnumPuser();
                leftnum1 = maxnum1;
                num1Idx = m;
            } else if (jiang.getLevel() != null && jiang.getLevel() == 2) {
                maxnum2 = jiang.getMaxnum() == null ? 0 : jiang.getMaxnum();
                maxnumPuser2 = jiang.getMaxnumPuser() == null ? 0 : jiang.getMaxnumPuser();
                leftnum2 = maxnum2;
                num2Idx = m;
            } else if (jiang.getLevel() != null && jiang.getLevel() == 3) {
                maxnum3 = jiang.getMaxnum() == null ? 0 : jiang.getMaxnum();
                maxnumPuser3 = jiang.getMaxnumPuser() == null ? 0 : jiang.getMaxnumPuser();
                leftnum3 = maxnum3;
                num3Idx = m;
            } else if (jiang.getLevel() != null && jiang.getLevel() == 4) {
                maxnum4 = jiang.getMaxnum() == null ? 0 : jiang.getMaxnum();
                maxnumPuser4 = jiang.getMaxnumPuser() == null ? 0 : jiang.getMaxnumPuser();
                leftnum4 = maxnum4;
                num4Idx = m;
            }
            m++;
        }

        //===待实现，定时任务清楚上一天缓存
        String rskey1 = Constants.REDIS_JIANG1_NUM + mpid + "_" + DateUtil.getToday();
        String rskey2 = Constants.REDIS_JIANG2_NUM + mpid + "_" + DateUtil.getToday();
        String rskey3 = Constants.REDIS_JIANG3_NUM + mpid + "_" + DateUtil.getToday();
        String rskey4 = Constants.REDIS_JIANG3_NUM + mpid + "_" + DateUtil.getToday();

        RAtomicLong along1 = redisService.getRAtomicLong(rskey1);
        RAtomicLong along2 = redisService.getRAtomicLong(rskey2);
        RAtomicLong along3 = redisService.getRAtomicLong(rskey3);
        RAtomicLong along4 = redisService.getRAtomicLong(rskey4);
        if (along1 != null && along2.get() > 0) leftnum1 -= along1.get();
        if (along2 != null && along2.get() > 0) leftnum2 -= along2.get();
        if (along3 != null && along3.get() > 0) leftnum3 -= along3.get();
        if (along4 != null && along4.get() > 0) leftnum4 -= along4.get();
        logger.info("--------------------------------------num1Idx =" + num1Idx);
        logger.info("--------------------------------------num2Idx =" + num2Idx);
        logger.info("--------------------------------------maxnum1 =" + maxnum1);
        logger.info("--------------------------------------maxnum2 =" + maxnum2);
        logger.info("--------------------------------------maxnum3 =" + maxnum3);

        Map<String, String> map = new HashMap<String, String>();
        map.put("cjdate", DateUtil.getToday());
        map.put("mpid", ObjectUtil.getMpid().toString());

        List<ChoujiangLog> list = choujiangLogService.getToujiang(DateUtil.getToday(), ObjectUtil.getMpid().toString());

        for (ChoujiangLog cjlog : list) {
            if (cjlog.getLevel() == 1) {
                leftnum1 -= cjlog.getNum();//getNum 代表中奖总数
            } else if (cjlog.getLevel() == 2) {
                leftnum2 -= cjlog.getNum();//getNum 代表中奖总数
            } else if (cjlog.getLevel() == 3) {
                leftnum3 -= cjlog.getNum();//getNum 代表中奖总数
            } else if (cjlog.getLevel() == 4) {
                leftnum4 -= cjlog.getNum();//getNum 代表中奖总数
            }
        }

        //maxnumPuser1>0才有效，不允许出现每人最高中0次
        //如果要出现每人最高中0次，则设置每日最高中奖数为0来达到该需求
        //我的中奖统计，1等奖几个，2等奖几个，3等奖几个，4等奖几个
        List<ChoujiangLog> mylist = choujiangLogService.getMyToujiang(ObjectUtil.getUid(), ObjectUtil.getMpid().toString());
        for (ChoujiangLog cjlog : mylist) {
            if (cjlog.getLevel() == 1 && maxnumPuser1 > 0) {
                myleftnum1 = cjlog.getNum() == 0 ? maxnumPuser1 : maxnumPuser1 - cjlog.getNum();//getGid 代表中奖总数
            } else if (cjlog.getLevel() == 2 && maxnumPuser2 > 0) {
                myleftnum2 = cjlog.getNum() == 0 ? maxnumPuser2 : maxnumPuser2 - cjlog.getNum();//getGid 代表中奖总数
            } else if (cjlog.getLevel() == 3 && maxnumPuser3 > 0) {
                myleftnum3 = cjlog.getNum() == 0 ? maxnumPuser3 : maxnumPuser3 - cjlog.getNum();//getGid 代表中奖总数
            } else if (cjlog.getLevel() == 4 && maxnumPuser4 > 0) {
                myleftnum4 = cjlog.getNum() == 0 ? maxnumPuser4 : maxnumPuser4 - cjlog.getNum();//getGid 代表中奖总数
            }
        }

        leftnum1 = myleftnum1 == -1 ? leftnum1 : myleftnum1 < leftnum1 ? myleftnum1 : leftnum1;
        leftnum2 = myleftnum2 == -1 ? leftnum2 : myleftnum2 < leftnum2 ? myleftnum2 : leftnum2;
        leftnum3 = myleftnum3 == -1 ? leftnum3 : myleftnum3 < leftnum3 ? myleftnum3 : leftnum3;
        leftnum4 = myleftnum4 == -1 ? leftnum4 : myleftnum4 < leftnum4 ? myleftnum4 : leftnum4;

        int random = (int) (1 + Math.random() * 10) % 8;
        //随机数
        while (true) {
            if (random == num1Idx) {
                if (leftnum1 == 0) {
                    logger.info("-----------------------------------------------------zhonglist random==num1Idx for random=" + random);
                    random = (int) (1 + Math.random() * 10) % 8;
                } else {
                    along1.incrementAndGet();
                    break;
                }
            } else if (random == num2Idx) {
                if (leftnum2 == 0) {
                    logger.info("-----------------------------------------------------zhonglist random==num2Idx for random=" + random);
                    random = (int) (1 + Math.random() * 10) % 8;
                } else {
                    along2.incrementAndGet();
                    break;
                }
            } else if (random == num3Idx) {
                if (leftnum3 == 0) {
                    logger.info("-----------------------------------------------------zhonglist random==num3Idx for random=" + random);
                    random = (int) (1 + Math.random() * 10) % 8;
                } else {
                    along3.incrementAndGet();
                    break;
                }
            } else if (random == num4Idx) {
                if (leftnum4 == 0) {
                    logger.info("-----------------------------------------------------zhonglist random==num3Idx for random=" + random);
                    random = (int) (1 + Math.random() * 10) % 8;
                } else {
                    along3.incrementAndGet();
                    break;
                }
            } else {
                break;
            }
        }
        info.setData(random);
        return info;
    }

    @RequestMapping("/api/choujiang/myzhonglist")
    @ResponseBody
    public Jinfo myzhonglist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                             @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);

        page = choujiangLogService.selectPage(page, new EntityWrapper<ChoujiangLog>()
                .setSqlSelect("id,name,uname,name,cjdate,pic,avatarpic,isguoqi,islingqu,jtype,cjid")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("uid", ObjectUtil.getUid())
                .eq("is_zhong", 1)
                .orderBy("id", false)
        );
        info.setInfo(page.getRecords());

        return info;
    }

    //活动奖品
    @RequestMapping("/api/choujiang/jiangs")
    @ResponseBody
    public Jinfo jiangs(long gid) {

        Jinfo info = new Jinfo();
        List<Choujiang> list = choujiangService.selectList(new EntityWrapper<Choujiang>()
                .eq("gid", gid)
                .orderBy("level")
        );
        info.setInfo(list);
        return info;
    }

    @RequestMapping("/admin/choujiang/sjadd")
    @ResponseBody
    public Jinfo sjadd(@Valid Choujiang bean, @RequestParam(value = "ywid", required = false) Long ywid, Model model) {
        //字段校验
        Jinfo info = new Jinfo();

        logger.info("==============================ywid=" + ywid);
        logger.info("==============================bean=" + bean);

        if (bean.getJtype() == Jptype.quan.getVal() && ywid != null && ywid > 0) {
            CouponTpl ctpl = couponTplService.selectById(ywid);
            if (ctpl != null) bean.setValue(ctpl.getCost().intValue());
            bean.setPic("https://img.niucaiduo.com/vmall/yx/quan.jpg");
        } else if (bean.getJtype() == Jptype.shanpin.getVal() && ywid != null && ywid > 0) {
            logger.debug("=====================ywid=" + ywid);
            Goods goods = goodsService.selectById(ywid);
            logger.debug("=====================goods=" + goods);

            if (goods != null) bean.setValue(goods.getPrice().intValue());
            if (Strings.isNullOrEmpty(bean.getPic())) bean.setPic(goods.getPic());
        } else if (bean.getJtype() == Jptype.xiexie.getVal()) {
            bean.setName("谢谢参与");
        } else if (bean.getJtype() == Jptype.jifen.getVal()) {
            bean.setPic("https://img.niucaiduo.com/vmall/yx/jifen.jpg");
        } else if (bean.getJtype() == Jptype.hongbao.getVal()) {
            bean.setPic("https://img.niucaiduo.com/vmall/yx/hongbao.jpg");
        }

        bean.setJid(ywid);
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        bean.setSid(ObjectUtil.getSid());
        bean.setGid(-ObjectUtil.getSid());
        bean.insert();

        List<CouponTpl> ctpl = couponTplService.getMechantCouponstpl(ObjectUtil.getMpid(), ObjectUtil.getMpid());
        List<Goods> goods = goodsService.selectList(new EntityWrapper<Goods>()
                .setSqlSelect("id,name,pic")
                .eq("mpid", ObjectUtil.getMpid())
                .orderBy("id", false)
        );

        model.addAttribute("couponTpls", ctpl);
        model.addAttribute("goods", goods);

        return info;
    }

    //中奖接口
    @RequestMapping("/api/choujiang/zhong")
    @ResponseBody
    public Jinfo zhong(Long gid) {

        Jinfo info = new Jinfo();
        info.setData(choujiangService.zhong(gid));
        return info;
    }

}
